//
//  CommonUtility.m
//  Rongcloud
//
//  Created by LiuLinhong on 2017/08/11.
//  Copyright © 2017年 Beijing Rongcloud Network Technology Co. , Ltd. All rights reserved.
//

#import "CommonUtility.h"
#import "NSString+Length.h"

@implementation CommonUtility

+ (BOOL)isFileExistsAtPath:(NSString *)url
{
    BOOL isDir = TRUE;
    BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:url isDirectory:&isDir];
    return isExist;
}

+ (NSArray *)getPlistArrayByplistName:(NSString *)plistName
{
    NSString *path = [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"];
    NSArray *array = [[NSArray alloc] initWithContentsOfFile:path];
    return array;
}

//+ (void)setButtonImage:(UIButton *)button imageName:(NSString *)name
//{
//    [button setImage:[UIImage imageNamed:name] forState:UIControlStateNormal];
//    [button setImage:[UIImage imageNamed:name] forState:UIControlStateHighlighted];
//}

+ (NSString *)getRandomString
{
    NSString *string = [[NSString alloc]init];
    for (int i = 0; i < 16; i++)
    {
        int number = arc4random() % 36;
        if (number < 10)
        {
            int figure = arc4random() % 10;
            NSString *tempString = [NSString stringWithFormat:@"%d", figure];
            string = [string stringByAppendingString:tempString];
        }
        else
        {
            int figure = (arc4random() % 26) + 97;
            char character = figure;
            NSString *tempString = [NSString stringWithFormat:@"%c", character];
            string = [string stringByAppendingString:tempString];
        }
    }
    return string;
}

+ (BOOL)isDownloadFileExists:(NSString *)fileName atPath:(NSString *)folderPath
{
    BOOL isDir = TRUE;
    BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:folderPath isDirectory:&isDir];
    if (!isExist)
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
        return NO;
    }
    
    NSString *tempDir = [folderPath stringByAppendingPathComponent:fileName];
    return [[NSFileManager defaultManager] fileExistsAtPath:tempDir] ? YES : NO;
}


+ (NSInteger)getRandomNumber:(int)fromValue to:(int)toValue
{
    return (NSInteger)(fromValue + (arc4random() % (toValue - fromValue + 1)));
}

+ (NSString *)hardwareUUID
{
    NSTask *task;
    task = [[NSTask alloc] init];
    [task setLaunchPath: @"/usr/sbin/ioreg"];
    
    //ioreg -rd1 -c IOPlatformExpertDevice | grep -E '(UUID)'
    
    NSArray *arguments;
    arguments = [NSArray arrayWithObjects: @"-rd1", @"-c",@"IOPlatformExpertDevice",nil];
    [task setArguments: arguments];
    
    NSPipe *pipe;
    pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];
    
    NSFileHandle *file;
    file = [pipe fileHandleForReading];
    
    [task launch];
    
    NSData *data;
    data = [file readDataToEndOfFile];
    
    NSString *string;
    string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
    
    //DLog (@"grep returned:n%@", string);
    
    NSString *key = @"IOPlatformUUID";
    NSRange range = [string rangeOfString:key];
    
    NSInteger location = range.location + [key length] + 5;
    NSInteger length = 32 + 4;
    range.location = location;
    range.length = length;
    
    NSString *UUID = [string substringWithRange:range];
//    UUID = [UUID stringByReplacingOccurrencesOfString:@"-" withString:@""];
    //DLog(@"UIID:%@",UUID);
    
    return UUID;  
}

+ (void)openGLViewReshape:(NSOpenGLView *)glView
{
        dispatch_async(dispatch_get_main_queue(), ^{
//            NSOpenGLView *glView = (NSOpenGLView *)self.meetingViewBuilder.localVideoView;
            [glView reshape];
        });
}

+ (NSString *)formatTimeFromDate:(NSDate *)date withFormat:(NSString *)format
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSTimeZone *timeZone = [NSTimeZone localTimeZone];
    [formatter setTimeZone:timeZone];
    [formatter setDateFormat:format];
    return [formatter stringFromDate:date];
}

#define StopwatchStart()
#define Profile(img)
#define StopwatchEnd(caption)

+ (NSImage *)createScreenShot
{
    // This just invokes the API as you would if you wanted to grab a screen shot. The equivalent using the UI would be to
    // enable all windows, turn off "Fit Image Tightly", and then select all windows in the list.
    StopwatchStart();
    CGImageRef screenShot = CGWindowListCreateImage(CGRectInfinite, kCGWindowListOptionOnScreenOnly, kCGNullWindowID, kCGWindowImageDefault);
    Profile(screenShot);
    StopwatchEnd("Screenshot");
    
    if (screenShot != NULL)
    {
        // Create a bitmap rep from the image...
        NSBitmapImageRep *bitmapRep = [[NSBitmapImageRep alloc] initWithCGImage:screenShot];
        // Create an NSImage and add the bitmap rep to it...
        NSImage *image = [[NSImage alloc] init];
        [image addRepresentation:bitmapRep];
        // Set the output view to the new NSImage.
//        [outputView setImage:image];
        CGImageRelease(screenShot);
        return image;
    }
    else
    {
        CGImageRelease(screenShot);
        return nil;
    }
}

+ (NSString *)strimCharacter:(NSString *)userName withRegex:(NSString *)regex
{
    NSString *nickName = userName;
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if ([predicate evaluateWithObject:userName]) {
        NSArray *subNames = [userName componentsSeparatedByString:@" "];
        if (subNames.count >= 1) {
            nickName = subNames.lastObject;
            if (nickName.length >= 2) {
                nickName = [userName substringWithRange:NSMakeRange(userName.length-2, 2)];
            }
        }
    }else{
        //
        NSArray *subNames = [userName componentsSeparatedByString:@" "];
        if (subNames.count >= 1) {
            nickName = subNames.lastObject;
            NSInteger length = [nickName getStringLengthOfBytes];
            if (length >= 5) {
                nickName = [nickName subBytesOfstringFromIndex:length-5];
            }
        }
    }
#pragma mark - 缺少中英文混合情况下最多5个字符的计算
    return nickName;
}

@end
